<?php

/**
 * @author 		Samuel Carlier
 * @package 	P3Base_Mailer
 * @subpackage 	P3Base_Mailer_Iterator
 */
class P3Base_Mailer_Iterator_MailHeader extends P3Base_Iterator_Simple {

	/**
	 * @const int
	 */
	const MAX_LINE_LENGHT = 80;

	/**
	 * according RFC 2822 lines cannot be longer then 1000 chars including CRLF
	 * but RECOMMENDED is creating lines no longer then 80 chars including CRLF
	 *
	 * long headers should also contain a space at the begin of a line
 	 *
	 * @return string
	 */
	public function current() {
		$name  = key($this->_array);
		$value = current($this->_array);

		$header = $name . ':' . $value;
		$header = str_replace(array("\n", "\r", "\r\n"), '', $header);
		//$header = chunk_split($header, 78,  P3Base_Mailer_Handler_SMTP::CRLF . ' ');

		$words  = explode(' ', $header);
		$count  = 0;
 
		$header = '';
		while(list(,$word) = each($words)) {
			$wc = strlen($word);

			if(($count + $wc + 2) >= self::MAX_LINE_LENGHT) {
				$header = rtrim($header) . P3Base_Mailer_Handler_SMTP::CRLF . ' ';
				$count = 0;
			}

			$header .= $word . ' ';
			$count = $count + $wc + 1;
		}

		$header = trim($header) . P3Base_Mailer_Handler_SMTP::CRLF;
		return $header;
	}
}
?>
